// import store from '@/store/index.js'
import { showToast } from '@/utils'

/**
 * @description 自动获取当前位置坐标
 * @param {Function} successCallback 成功回调
 * @param {Function} failureCallback 失败回调
 */
export function getCurrentLocationCoordinate(
  successCallback: (data: any) => void,
  failureCallback?: (msg: string) => void,
) {
  uni.getLocation({
    type: 'gcj02',
    geocode: true,
    success(res) {
      console.log('RESPONSE-自动获取当前位置坐标-uni.getLocation：', res)
      let object = {
        latitude: res.latitude,
        longitude: res.longitude,
      }
      successCallback && successCallback(object)
    },
    fail(err) {
      console.log('ERROR-自动获取当前位置坐标-uni.getLocation：', err)
      failureCallback && failureCallback('授权拒绝')
    },
  })
}

/**
 * @description 手动选择位置
 * @param {Function} successCallback 成功回调
 */
export function manualChooseLocation(successCallback: any) {
  uni.getLocation({
    type: 'gcj02',
    success: (res: any) => {
      console.log('RESPONSE-手动选择位置-uni.getLocation：', res)
      _chooseLocationInfo(res.latitude, res.longitude, successCallback)
    },
    fail: (err) => {
      console.log('ERROR-手动选择位置-uni.getLocation：', err)
      uni.showModal({
        content: '授权‘咪婴伴侣’获取位置信息',
        confirmColor: '#36C7B5',
        success: (res: any) => {
          if (res.confirm) {
            wx.getLocation({
              success(res) {
                _chooseLocationInfo(res.longitude, res.latitude, successCallback)
              },
            })
          } else {
            showToast('用户取消授权！')
          }
        },
      })
    },
    complete: (res) => {
      console.log('COMPLETE-手动选择位置-uni.getLocation：', res)
    },
  })
}

/**
 * @description 打使用应用内置地图查看位置
 * @param {object} { longitude经度, latitude纬度, name地址名称, address地址详情 }
 * @return void
 * @注意 name和address非必传
 */
export function openLocation(params: {
  longitude: number
  latitude: number
  name: string
  address: string
}): void {
  const { longitude, latitude, name, address } = params
  uni.openLocation({
    latitude,
    longitude,
    name,
    address,
    success: (res) => {
      console.log('SUCCESS-打开内置地图：', res)
    },
    fail: (err) => {
      showToast('打开地图失败！')
      console.log('ERROR-打开内置地图：', err)
    },
  })
}

/**
 * @description 内部方法 - 经纬度转换为地址
 * @param {string} longitude 经度
 * @param {string} latitude 纬度
 * @param {Function} successCallback 成功回调
 */
function _chooseLocationInfo(longitude: any, latitude: any, successCallback: any) {
  uni.chooseLocation({
    latitude,
    longitude,
    success: (resp) => {
      if (successCallback) {
        successCallback({
          name: resp.name,
          detail: resp.address,
          latitude: resp.latitude,
          longitude: resp.longitude,
        })
      }
    },
    fail: (error) => {
      console.log('chooseLocation', error)
    },
  })
}
